import { ElMessageBox } from "element-plus";
import SvgIcon from "@/components/svg-icon/index.vue";
import { h } from "vue";
import "./src/main.scss";
import { systemAppStore } from "@/stores/system";
interface MESSAGE_BOX_DEFAULT_OPTS {
  alert: {
    closeOnPressEscape: boolean;
    closeOnClickModal: boolean;
  };
  confirm: object;
  prompt: { showInput: boolean };
}

const MessageBox: any = function (options: any, appContext: any) {
  options = options || {};
  if (typeof options === "string") {
    options = {
      message: options
    };
  }
  options = Object.assign(
    {
      closeOnClickModal: false,
      closeOnPressEscape: true,
      closeOnHashChange: true,
      cancelButtonText: "取消",
      confirmButtonText: "确定",
      showCancelButton: true
    },
    {
      center: false // 会导致icon到标题栏
    },
    options,
    {
      customClass: [
        "ps-message-box",
        `${options.boxType || "default"}-message-box`,
        options.center ? "is-center" : "",
        options["customClass"],
        options.iconClass ? "ps-message-" + options.iconClass : ""
      ]
        .filter((it) => it)
        .join(" "),
      confirmButtonClass: [
        options["confirmButtonClass"] || "message-confirm-btn"
      ]
        .filter((it) => it)
        .join(" "),
      cancelButtonClass: [options["cancelButtonClass"] || "message-cancel-btn"]
        .filter((it) => it)
        .join(" "),
      title:
        typeof options.title === "undefined"
          ? systemAppStore().appCfg.name
          : options.title
    }
  );
  if (options.iconClass) {
    options.icon = h(SvgIcon, {
      iconClass: options.iconClass,
      ...(options.iconSize ? { size: options.iconSize } : {})
    });
  }
  return ElMessageBox(options, appContext);
};
const MESSAGE_BOX_DEFAULT_OPTS: MESSAGE_BOX_DEFAULT_OPTS = {
  alert: { closeOnPressEscape: false, closeOnClickModal: false },
  confirm: {},
  prompt: { showInput: true }
};
["alert", "confirm", "prompt"].forEach((boxType: string) => {
  MessageBox[boxType] = (
    message: string,
    title: string,
    options: any,
    appContext: any
  ) => {
    let titleOrOpts;
    if (title && typeof title === "object") {
      options = title;
    } else if (typeof title !== "undefined") {
      titleOrOpts = title;
    }
    return MessageBox(
      Object.assign(
        {
          title: titleOrOpts,
          message,
          type: "",
          ...MESSAGE_BOX_DEFAULT_OPTS[boxType as keyof MESSAGE_BOX_DEFAULT_OPTS]
        },
        options,
        {
          boxType
        }
      ),
      appContext
    );
  };
});
MessageBox["close"] = function () {
  ElMessageBox.close();
};
export default MessageBox;
